package com.qfedu.hotelssm.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.qfedu.hotelssm.dao.PropertyDao;
import com.qfedu.hotelssm.entity.Property;
import com.qfedu.hotelssm.service.intf.PropertyService;
import com.qfedu.hotelssm.vo.PageBean;
import com.qfedu.hotelssm.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class PropertyServiceImpl implements PropertyService {
    @Autowired
    private PropertyDao dao;

    @Override
    public R save(Property property) {
        if(dao.save(property)>0){
            return R.ok();
        }else {
            return R.fail();
        }
    }

    @Override
    public R delete(int id) {
        if(dao.delete(id)>0){
            return R.ok();
        }else {
            return R.fail();
        }
    }

    @Override
    public R update(Property property) {
        if(dao.update(property)>0){
            return R.ok();
        }else {
            return R.fail();
        }
    }

    @Override
    public PageBean selectPage(String sumProfit, int page, int limit) {
        if (sumProfit == null || sumProfit.length()==0) {
            Double sum = 0.001d;
            int start = (page - 1) * limit;
            return new PageBean((int) dao.selectCount(sum), dao.selectPage(sum, start, limit));
        }else{
            Double sum = Double.parseDouble(sumProfit);
            int start = (page - 1) * limit;
            return new PageBean((int) dao.selectCount(sum), dao.selectPage(sum, start, limit));
        }
    }

    @Override
    public R deleteByIds(int[] ids) {
        if (ids != null) {
            if (dao.deleteByIds(ids) > 0) {
                return R.ok();
            }
        }
        return R.fail();
    }

    @Override
    public List<Property> download() {
        return dao.all();
    }

    @Override
    public R upload(MultipartFile file) throws IOException {
        if (!file.isEmpty()){
            List<Property> list = EasyExcel.read(file.getInputStream(), Property.class, new ReadListener() {
                @Override
                public void invoke(Object o, AnalysisContext analysisContext) {}
                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {}
            }).sheet().doReadSync();
            if (dao.saveBatch(list) > 0){
                return R.ok();
            }
        }
        return R.fail();
    }
}
